package com.fjl.code.zz;

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class LinkedListCycle {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;         // 慢指针走一步
            fast = fast.next.next;    // 快指针走两步

            if (slow == fast) {       // 快慢指针相遇，说明有环
                return true;
            }
        }

        return false;  // 遍历结束后 fast 为空，说明无环
    }
}
